<!--
 * @Author: 清羽
 * @Date: 2022-08-25 10:34:28
 * @LastEditTime: 2022-08-31 09:59:16
 * @LastEditors: you name
 * @Description: 
-->
<!-- addStepsThree 页 -->
<template>
  <div class="addStepsThree">

    <el-form label-width="120px">
      <el-form-item label='商品详情:'>
        <Editor
          :tinyvalue='content'
          @tinymceinput="gettinymceinput"
        ></Editor>
      </el-form-item>

      <el-divider></el-divider>

      <el-form-item label="商品规格树：">
        <div v-for="item in ProductParamTree">
          <el-row>
            <div class="productParam">
              <el-col>
                <!-- 规格组 -->
                <el-tag
                  class="productParamGroup"
                  closable
                  :disable-transitions="false"
                  @close="delProductParamGroup(item._id)"
                >{{item.product_group_name}}</el-tag>
                <!-- 规格值 -->
                <el-row :gutter="10">
                  <el-col
                    :span="1.5"
                    v-for="tag in item.key"
                  >
                    <el-tag
                      closable
                      :disable-transitions="false"
                      @close="delProductParamKey(tag._id)"
                    >
                      {{tag.product_key_name}}
                    </el-tag>
                  </el-col>

                  <el-col :span="1.5">
                    <el-input
                      class="input-new-tag"
                      v-model="item.inputValue"
                      ref="saveTagInput"
                      size="small"
                      :placeholder="`+ 添加`+item.product_group_name+`的值`"
                      @keyup.enter.native="addProductParamKey(item)"
                      @blur="addProductParamKey(item)"
                    >
                    </el-input>
                    <p
                      v-if="!productFromValue[0]&&!item.key[0]"
                      style="font-size: 14px; color: #F56C6C;"
                    ><i class="el-icon-warning"></i>请完善规格创建,才能显示规格表单</p>
                    <!-- <el-input
                  class="input-new-tag"
                  v-if="inputVisible"
                  v-model="item.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="addProductParamKey(item)"
                  @blur="addProductParamKey(item)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(item._id)"
                >+ 添加{{item.product_group_name}}的值</el-button> -->

                  </el-col>

                </el-row>

              </el-col>
            </div>
          </el-row>

        </div>

      </el-form-item>
      <!-- 规格树 end -->

      <el-form-item>
        <el-row :gutter="20">

          <el-col :span="4">
            <el-input
              placeholder="请输入规格组名"
              v-model="productGroupName"
              clearable
            >
            </el-input>
          </el-col>

          <el-col :span="7">
            <el-button @click="addGroupName">添加规格组</el-button>
          </el-col>

        </el-row>
        <!-- 创建规格组 end -->
      </el-form-item>

      <el-divider></el-divider>

      <div
        class="form"
        v-loading="formLoading"
      >
        <table id="customers">
          <tr>
            <th v-for="(item, index) in productFromGroup">{{ item }}</th>
            <th v-for="(item, index) in fixedFromGroup">{{ item }}</th>
          </tr>
          <template v-for="(item,index) in productFromValue">
            <tr :key="index">
              <td v-for="(ii,indexss) in item.value">
                {{ ii }}
              </td>
              <!-- 商品图片 -->
              <td>
                <div class="imgSelect">
                  <!-- {{ item }} -->
                  <el-image
                    v-if="item.data.pic"
                    :src="baseUrl+item.data.pic"
                    @click="openProductPic(index,0)"
                    style="width:100px ;height: 100px; cursor: pointer;"
                    fit="scale-down"
                  >
                  </el-image>
                  <i
                    v-else
                    slot="default"
                    class="el-icon-plus"
                    @click="openProductPic(index,0)"
                  ></i>

                </div>
              </td>
              <!-- 商品轮播图 -->
              <td>
                <div
                  v-if="item.data.picListObj"
                  class="slideshowList"
                >
                  <el-image
                    style="width:100px ;height: 100px; cursor: pointer;"
                    fit="scale-down"
                    v-for="(i,indexx) in item.data.picListObj"
                    :src="baseUrl+i"
                    @click="openProductPic(index,1,indexx)"
                  ></el-image>
                  <!-- <div v-for="(i,index) in item.data.picList">
                  {{i}}
                </div> -->
                  <i
                    v-if="item.data.picListArr.length<5"
                    slot="default"
                    class="el-icon-plus"
                    @click="openProductPic(index,1)"
                  ></i>
                </div>
                <div
                  class="slideshowList"
                  v-else
                >
                  <i
                    slot="default"
                    class="el-icon-plus"
                    @click="openProductPic(index,1)"
                  ></i>
                </div>
              </td>
              <!-- 商品库存 -->
              <td style="width: 5rem;">
                <!-- <el-input v-model="item.data.stock" /> -->
                <el-input-number
                  v-model="item.data.stock"
                  :min="0"
                  :step="1"
                />
                <!-- {{item}} -->
              </td>
              <!-- 商品价格 -->
              <td style="width: 5rem;">
                <!-- <el-input v-model="item.data.price" /> -->
                <el-input-number
                  v-model="item.data.price"
                  :min="1"
                  :precision="2"
                  :step="1"
                />
              </td>

            </tr>
          </template>

          <el-dialog
            title="图片素材"
            :visible.sync="dialogVisible"
            width="80%"
            :before-close="handleClose"
          >

            <div>
              <el-upload
                class="upload-demo"
                action
                :http-request="handleUploadFile"
                :with-credentials='true'
                :on-success="successUpload"
                multiple
                :limit="3"
                :file-list="fileList"
                :show-file-list="false"
              >
                <el-button
                  size="small"
                  type="primary"
                  data-title="点击上传"
                >点击上传</el-button>
                <div
                  slot="tip"
                  class="el-upload__tip"
                >只能上传jpg/png文件，且不超过500kb</div>
              </el-upload>
            </div>

            <el-divider></el-divider>

            <div class="productPicList">

              <div
                v-for="(item,index) in imgList"
                class="item"
              >
                <el-image
                  :src="baseUrl+item.product_pic_path"
                  fit="scale-down"
                  :preview-src-list="previewList"
                >

                </el-image>

                <el-row>
                  <el-col :span="24">
                    <el-checkbox
                      v-model="item._id"
                      @change="checkPic(item.product_pic_path)"
                    >选择</el-checkbox>

                  </el-col>

                  <el-col
                    :span="24"
                    centent
                  >
                    <el-button
                      type="text"
                      @click="delPic(item._id)"
                    >
                      删除
                    </el-button>
                  </el-col>
                </el-row>

              </div>

            </div>

            <span
              slot="footer"
              class="dialog-footer"
            >
              <el-button @click="dialogVisible = false">取 消</el-button>
              <el-button
                type="primary"
                @click="dialogVisible = false"
              >确 定</el-button>
            </span>
          </el-dialog>
          <!-- 图片素材选择 弹窗end -->
        </table>
      </div>
      <!-- 规格表单 end -->
    </el-form>

    <el-divider></el-divider>

    <div>
      <el-button
        style="margin-top: 12px;"
        @click="previous"
        icon="el-icon-arrow-left"
      >上一步</el-button>
      <el-button
        style="margin-top: 12px;"
        type="primary"
        @click="next"
      >下一步<i class="el-icon-arrow-right el-icon--right"></i></el-button>
    </div>
    <!-- 上下页button end -->
  </div>
</template>

<script>
import { addProductGroupName, getProductParam, delProductParamGroup, addProductParamKey, delProductParamKey, getProductPic, uploadProductPic, delProductPic, submitProductParam, getProductParamValue } from "@/api/business/product"
// import Editor from "@/components/Editor/index.vue"
import Editor from "@/components/TinymceEditor/index.vue"

export default {
  name: "addStepsThree",
  data () {
    return {
      content: "",
      titleText: "替换标题文本",
      productGroupName: "", // 商品规格组名
      productId: this.$route.query.productId,
      ProductParamTree: [], // 规格树
      inputVisible: false,
      inputValue: '',       // 输入的值
      dialogVisible: false, // 图片素材选择的弹窗
      imgList: [],          // 图片素材缩略图列表
      previewList: [],      // 图片素材放大缩略图数据列表
      baseUrl: this.$baseUrl,
      checkPicUrl: '',      // 选中的图片路径
      checkPicIndex: '',    // 选中的图片索引
      validatorImgType: '', // 0:选择图片 1:选择轮播图
      slideshowIndex: '',    // 选中轮播图里的图片索引
      fileList: [],
      dynamicTags: ['标签一', '标签二', '标签三'],
      productFromValue: [],
      productFromGroup: [],
      fixedFromGroup: [],
      fixedFromValue: [],
      formLoading: true,
      treeLoading: true
    }
  },
  components: { Editor },
  // 生命周期 - 创建完成（访问当前this实例）
  created () {
    this.getProductParam()
  },
  // 生命周期 - 挂载完成（访问DOM元素）
  mounted () {

  },
  // 函数
  methods: {

    gettinymceinput (val) {
      this.content = val;
      // console.log(this.fathertinyvalue, "看实时变动的父组件获取的数据");
    },

    delPic (value) { // 删除商品图片素材里的图片
      // console.log("delPic => value", value)
      const data = { picId: value }
      delProductPic(data).then(res => {
        if (res.data.msg == "操作成功") {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        } else {
          this.$message.error(res.data.msg)
        }
        this.getProductPic()
      })

    },
    async handleUploadFile (params) { // 重写上传方法
      const file = params.file
      // 使用FormData传参数和文件
      // 根据后台需求数据格式
      const form = new FormData();
      // 文件对象
      form.append("product_pic", file);
      form.append("productId", this.productId)
      // console.log("product_pic => ", form.get("product_pic"))
      // console.log("productId => ", form.get("productId"))
      await uploadProductPic(form).then(res => {
        if (res.data.msg == "操作成功") {
          this.$message({
            message: res.data.msg,
            type: 'success'
          });
        }
      })
    },
    successUpload () {  // 上传成功
      this.getProductPic()
    },
    checkPic (value) { // 选择图片
      // console.log("checkPic => value", value)
      this.dialogVisible = false
      this.checkPicUrl = value
      // console.log("checkPic => this.checkPic", this.checkPicUrl)
      const urlValue = this.checkPicIndex
      // console.log("checkPic => urlValue", urlValue)
      // this.productFromValue[urlValue].data = {}
      if (this.validatorImgType == 0) {
        // console.log("当前选择的是商品图片")
        this.productFromValue[urlValue].data.pic = this.checkPicUrl
      } else if (this.validatorImgType == 1) {
        // console.log("当前选择的是轮播图")
        if (!this.productFromValue[urlValue].data.picListArr) {
          this.productFromValue[urlValue].data.picListArr = []
        }
        if (this.slideshowIndex) {
          const index = this.slideshowIndex
          // console.log("checkPic => index", index)
          this.productFromValue[urlValue].data.picListObj[index] = this.checkPicUrl
        } else {
          this.productFromValue[urlValue].data.picListArr.push(this.checkPicUrl)
          this.productFromValue[urlValue].data.picListObj = { ...this.productFromValue[urlValue].data.picListArr }
        }
      }

    },

    getProductPic () { // 获取图片素材
      const query = { productId: this.productId }
      getProductPic(query).then(res => {  // 获取图片素材
        this.imgList = res.data.data      // 图片缩略图组
        for (var i in this.imgList) {
          this.previewList[i] = this.$baseUrl + this.imgList[i].product_pic_path  // 放大图片组
        }
      })
    },

    openProductPic (value, type, slideshowIndex) {  // 选择列表
      // console.log("openProductPic => slideshowIndex", slideshowIndex)
      this.dialogVisible = true
      if (slideshowIndex) {
        this.slideshowIndex = slideshowIndex
        // console.log("openProductPic =>  this.slideshowIndex", this.slideshowIndex)
        // console.log("openProductPic => slideshowIndex", slideshowIndex)
      } else {
        this.slideshowIndex = ""
        // console.log("openProductPic => v", type)
        this.validatorImgType = type
        this.checkPicIndex = value
        // console.log("openProductPic => value", value)
        // this.dialogVisible = true
        this.getProductPic()  // 获取图片素材
        // const query = { productId: this.productId }
        // getProductPic(query).then(res => {  // 获取图片素材
        //   this.imgList = res.data.data      // 图片缩略图组
        //   for (var i in this.imgList) {
        //     this.previewList[i] = this.$baseUrl + this.imgList[i].product_pic_path  // 放大图片组
        //   }
        // })
      }
    },

    handleClose (done) {

      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => { });
    },

    async getProductParam () { // 获取商品规格
      const query = { productId: this.productId }
      await getProductParam(query).then(res => {
        this.productFromValue = res.data.fromValue
        // console.log("getProductParam => this.productFromValue", this.productFromValue)
        this.productFromGroup = res.data.fromGroup
        this.fixedFromGroup = res.data.fixedFromGroup
        this.fixedFromValue = res.data.fixedFromValue
        this.ProductParamTree = res.data.data
        // console.log("getProductParam => this.ProductParamTree", this.ProductParamTree)
        this.formLoading = false
      })

      await getProductParamValue(query).then(res => {
        const product = res.data.data
        // console.log("awaitgetProductParamValue => res.data", res.data)
        if (product.length !== 0) {
          for (var i in this.productFromValue) {
            this.productFromValue[i].data.price = product[i].product_price
            this.productFromValue[i].data.stock = product[i].product_stock
            this.productFromValue[i].data.pic = product[i].product_pic
            this.productFromValue[i].data.picListArr = product[i].product_slider_image
            this.productFromValue[i].data.picListObj = { ...product[i].product_slider_image }
          }
          this.formLoading = false
        }
      })

    },

    addGroupName () { // 添加商品规格组
      const data = { productGroupName: this.productGroupName, productId: this.productId }
      addProductGroupName(data).then(res => {
        this.$message({
          type: 'success',
          message: res.data.msg
        })
        this.productGroupName = ''
        this.getProductParam()
      })
    },

    delProductParamGroup (value) { // 删除规格组
      const query = { productGroupId: value }
      delProductParamGroup(query).then(res => {
        this.$message({
          type: 'success',
          message: res.data.msg
        })
        this.getProductParam()
      })
    },

    addProductParamKey (value) { // 在 Input 失去焦点时触发 ---添加规格项
      let inputValue = value.inputValue;
      if (inputValue !== undefined) {
        const data = { productKeyName: inputValue }
        const query = { productId: this.productId, productGroupId: value._id }
        addProductParamKey(query, data).then(res => {
          this.$message({
            type: 'success',
            message: res.data.msg
          })
          this.getProductParam()
        })
        // if (inputValue) {
        //   this.dynamicTags.push(inputValue);
        // }
        // this.inputVisible = false;
        // this.inputValue = '';
      }
      // this.inputVisible = false;

    },

    // 删除规格组的值 ---规格项
    delProductParamKey (value) {
      // console.log("delProductParamKey => value", value)
      const query = { productKeyId: value }
      delProductParamKey(query).then(res => {
        this.$message({
          type: 'success',
          message: res.data.msg
        })
        this.getProductParam()
      })
    },

    // showInput (value) { // 点击按钮显示输入框
    //   console.log("showInput => value", value)
    //   this.inputVisible = true;
    //   this.$nextTick(_ => {
    //     this.$refs.saveTagInput.$refs.input.focus();
    //   });
    // },
    // 上一步
    previous () {
      this.$emit('active', 1)
    },
    // 下一步
    next () {
      // content
      const data = { value: this.productFromValue, editor: this.content }
      const query = { productId: this.productId }
      submitProductParam(query, data).then(response => {
        // console.log("submitProductParam => response", response.data)
        this.$message({
          message: response.data.msg,
          type: 'success'
        });
        this.$emit('active', 3)
      })
    }
  }
}
</script>
<style lang="scss" scoped>
/* @import url(); 引入css类 */
.addStepsThree {
  .el-row {
    margin-bottom: 1rem;
    .productParamGroup {
      margin-bottom: 1rem;
      background: #fff0;
      font-weight: 700;
      color: #303133;
      font-size: 16px;
      border: none;
    }
  }
}
::v-deep .productParamGroup .el-icon-close {
  background: #c0c4cc;
  color: #fff;
  &:hover {
    background: #999;
  }
}

.form {
  min-width: 1269px;
  #customers {
    font-family: Arial, Helvetica, sans-serif;
    border-collapse: collapse;
    // min-width: 1269px;
    width: 100%;
    overflow-x: scroll;
    overflow-y: hidden;
  }
}

#customers td,
#customers th {
  border: 1px solid #ddd;
  padding: 8px;
}

#customers tr:nth-child(even) {
  background-color: #f2f2f2;
}

#customers tr td {
  transition: all 0.5s;
  -webkit-transition: all 0.5s;
}
// #customers tr:hover {
//   background-color: #ddd;
// }
#customers tr:hover td {
  background-color: #ddd;
}

#customers th {
  padding-top: 12px;
  padding-bottom: 12px;
  text-align: left;
  background-color: #4caf50;
  color: white;
}

.imgSelect {
  display: flex;
  justify-content: center;
  align-items: center;
  // .el-icon-plus {
  //   width: 100px;
  //   height: 100px;
  //   // background: #4caf50;
  //   border-radius: 6px;
  //   display: flex;
  //   justify-content: center;
  //   align-items: center;
  //   background-color: #fbfdff;
  //   border: 1px dashed #c0ccda;
  //   border-radius: 6px;
  //   box-sizing: border-box;
  //   // width: 148px;
  //   // height: 148px;
  //   cursor: pointer;
  //   line-height: 146px;
  //   vertical-align: top;
  // }
}
.slideshowList {
  display: grid;
  grid-template-columns: repeat(5, 5fr);
  align-items: center;
  justify-items: center;
  /* justify-content属性是整个内容区域在容器里面的水平位置（左中右），align-content属性是整个内容区域的垂直位置（上中下）。 */
  justify-content: center;
  align-content: center;
}
tr {
  .el-image {
    transition: all 0.3s;
    -webkit-transition: all 0.3s;
    &:hover {
      transform: scale(1.3);
      z-index: 2;
      // background-color: #fbfdff;
    }
  }
}

.el-icon-plus {
  width: 100px;
  height: 100px;
  // background: #4caf50;
  border-radius: 6px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #fbfdff;
  border: 1px dashed #c0ccda;
  border-radius: 6px;
  box-sizing: border-box;
  // width: 148px;
  // height: 148px;
  cursor: pointer;
  line-height: 146px;
  vertical-align: top;
}
.productPicList {
  display: grid;
  // grid-template-columns: 1fr 1fr 1fr 1fr 1fr 1fr;
  grid-template-columns: repeat(6, 6fr);
  gap: 1rem;
  // background: #f5f5f5;
  .item {
    width: 100%;
    height: 100%;
    box-shadow: 0 5px 15px rgba(188, 186, 186, 0.3);
    // transition: box-shadow 0.5s ease, transform 0.2s ease;
    // &:hover {
    //   box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
    // }
    .el-image {
      height: 150px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .el-row .el-col {
      margin-top: 5px;
      display: flex;
      justify-content: center; /*主轴上居中*/
      align-items: center; /*侧轴上居中*/
    }
  }
}

body {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  transform-style: preserve-3d;
  transform: perspective(800px);
}
</style>